package com.fwj.utils;

import com.fwj.exception.EsbSynException;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 执行前迁移f5-data数据到 f5-his
 */
public class DataMigration {

    public static void dataFileToHis(List<String> fileList, String shHis)  {

        if (fileList.isEmpty()||fileList.size()==0)
            return;
        File sh_his_file = new File(shHis);

        for (int i=0;i<fileList.size();i++){
            String sh_file_path = fileList.get(i);
            File sh_path = new File(sh_file_path);

            //如果存在,则迁移
            if(sh_path.exists() ){
                try {
                    //如果目录下已经存在，则删除。
                    existsDelete(shHis,sh_path.getName());
                    FileUtils.moveFileToDirectory(sh_path,
                            sh_his_file,false );
                } catch (IOException e) {
                    e.printStackTrace();

                    throw new EsbSynException("迁移sh文件失败!");
                }
            }
        }



    }public static void existsDelete(String dirPath,String fileName) {
        File pathFile = new File(dirPath);
        if(!pathFile.exists() || pathFile.isFile()) {
            return;
        }
        for(File file:pathFile.listFiles()) {
            if(file.isFile() && fileName.equals(file.getName())) {
                file.delete();
                break;
            }
        }
    }

    public static void dataToHis(String shPath,String shHis)  {
            File  dataFile = new File(shPath);
        File hisFile = new File(shHis);
        if(!dataFile.exists() ){
            //如果不存在,则创建.
            if(dataFile.isDirectory()){
                dataFile.mkdir();
            }
            return;
        }

            try {
                //如果发现有文件,则迁移.
                // 业务需求.如果his目录下有相应的
              //  if(sh_file.isDirectory()) {
                File[] files = dataFile.listFiles();
                if(files.length>0){
                    for (int i=0;i<files.length;i++){
                        File sh_file = files[i];

                        //如果目录下已经存在，则删除。
                        existsDelete(shHis,sh_file.getName());
                            FileUtils.moveFileToDirectory(sh_file,
                                    hisFile,true );

                    }
                }
            //    }
            } catch (IOException e) {
                e.printStackTrace();

                throw new EsbSynException("迁移sh文件失败!");
            }


    }
}
